package mathe;

public class Polynom{
  double[] koeffs;

  public Polynom(double[] f){
    koeffs=f;
  }

  public int grad(){return koeffs.length-1;}

  public double[] getKoeff(){return koeffs;}

  public Polynom nimmMalMit(Polynom p){
    int m=koeffs.length, n=p.koeffs.length;
    double[] neu=new double[m+n-1];
    for(int i=0; i<m; i++)
      for(int j=0; j<n; j++)
        neu[i+j]+=koeffs[i]*p.koeffs[j];
    return new Polynom(neu);
  }

  public String toString(){
    int len=koeffs.length;
    if(len==0) return ""+koeffs[0];
    StringBuffer sb=new StringBuffer(6*len);
    for(int i=0; i<len; i++){
      double f=koeffs[i];
      if(f==0) continue;
      if(i==0){
        sb.append(f);
        continue;
      }
      if(f>0){
        sb.append("+");
        if(f!=1) sb.append(f);
      } else{
        sb.append("-");
        if(f!=-1) sb.append(-f);
      }
      sb.append("x^"+i);
    }
    return sb.toString();
  }

  public Polynom nimmMalMit(double k){
    double[] neu=koeffs.clone();
    for(int i=0; i<koeffs.length; i++) neu[i]*=k;
    return new Polynom(neu);
  }

  public boolean equals(Object obj){
    if(!(obj instanceof Polynom)) return false;
    Polynom p=(Polynom)obj;
    if(p.koeffs.length!=koeffs.length) return false;
    for(int i=0; i<koeffs.length; i++)
      if(koeffs[i]!=p.koeffs[i]) return false;
    return true;
  }
}
